import { message, Button, Form, Input } from 'antd'
import { WordsInput } from '@/desktop/components/words'
import services from '@/services'
import { WordType } from '@/services/common/definition'
import type { BaseWelcomeConfig, MessageVariable } from '@/services/features/normal-welcome'
import type { EditingConfig } from '.'
import './edit-config.module.less'

export default function EditConfig(props: {
  config: EditingConfig
  goPrev: (editedConfig: EditingConfig) => void
  onFinish: () => void
}) {
  const { config: initialConfig, goPrev, onFinish } = props
  const [form] = Form.useForm<EditingConfig>()

  const onGoPrev = useCallback(() => {
    const values = form.getFieldsValue()
    goPrev(values)
  }, [form, goPrev])

  const [submitting, setSubmitting] = useState(false)
  const onSubmit = useCallback(
    async (values: BaseWelcomeConfig) => {
      setSubmitting(true)
      const res = await services.features.normalWelcome.addOrUpdateConfig({
        id: initialConfig.id,
        ...values,
      })
      setSubmitting(false)

      if (res.success) {
        void message.success('保存成功！')
        onFinish()
      } else {
        void message.warning(`保存失败：${res.error}`)
      }
    },
    [initialConfig, onFinish],
  )

  const [variables, setVariables] = useState<MessageVariable[]>([])
  useEffect(() => {
    void services.features.normalWelcome.loadVariables().then(res => {
      if (res.success) setVariables(res.data)
    })
  }, [])
  const inputVariables = useMemo(() => {
    return [
      { name: '好友昵称', symbol: '{WxName}' },
      ...variables.map(v => ({ name: v.name, symbol: `{${v.name}}` })),
    ]
  }, [variables])

  return <Form
    styleName="form"
    form={form}
    initialValues={initialConfig}
    labelCol={{ span: 4 }}
    onFinish={onSubmit}
  >
    <Form.Item hidden name="id">
      <Input />
    </Form.Item>
    <Form.Item hidden name="enable">
      <Input />
    </Form.Item>
    <Form.Item hidden name="wxids">
      <Input />
    </Form.Item>

    <Form.Item label="欢迎语名称" name="name" rules={[{ required: true }]}>
      <Input maxLength={30} />
    </Form.Item>

    <Form.Item name="content" label="欢迎语类型" rules={[{ required: true }]}>
      <WordsInput
        extraTypes={[WordType.GroupInvite]}
        editorProps={{
          [WordType.Text]: {
            variables: inputVariables,
            variablesLabel: <span>插入变量：</span>,
          },
        }}
      />
    </Form.Item>

    <Form.Item styleName="actions">
      <Button disabled={submitting} onClick={onGoPrev}>
        上一步
      </Button>
      <Button loading={submitting} type="primary" htmlType="submit">
        完成
      </Button>
    </Form.Item>
  </Form>
}
